// ignore_for_file: must_be_immutable

/*
 * @Author: CodeHare
 * @Date: 2023-09-27 10:59:53
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-05-15 17:13:22
 * @Description: 充电桩详情页
 */

import 'package:get/get.dart';
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/text_width.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/model/data_type_config.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/components/timer_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/pages/devices/device_tab/components/child_device_widget.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/charging_station/charging_station_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/charging_station/widgtes/charge_overview.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/charging_station/widgtes/charge_station_power_line_chart.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/charging_station/widgtes/charge_station_trends_chart.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/charging_station/widgtes/electrocity_fullscreen_chart.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/charging_station/widgtes/power_fullscreen_chart.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/dynamic_tabview.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/stastics_info_widget.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/new_air_cooling_page_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/new_air_cooling_page_model.dart';
import 'package:yt_devops/pages/devices/device_tab/utils/device_util.dart';
import 'package:yt_devops/components/my_gesture_detector.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_mains_elec_detail/keep_aliver_wrapper.dart';
import 'package:yt_devops/pages/site/site_statis_data/show_full_screen_btn.dart';
import 'package:yt_devops/pages/site/widgets/statistics_itme_widget.dart';
import 'package:yt_devops/pages/site/widgets/statistics_time_unit_tab.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';

class ChargingStationView extends GetView<ChargingStationController> {
  DeviceModel? deviceInfo;

  ChargingStationView({Key? key, this.deviceInfo}) : super(key: key);

  @override
  ChargingStationController get controller =>
      Get.put(ChargingStationController());
  var actionKey = GlobalKey();
  final divider = Divider(height: 1.h, indent: 16.w, endIndent: 16.w);

  Widget _createText(String? value, color, fontSize) {
    return Text(
      (value == null || value.isEmpty) ? '--' : value,
      style: TextStyle(color: color, fontSize: fontSize),
      maxLines: 2,
      textAlign: TextAlign.right,
    );
  }

  /// 功率折线图
  Widget _generatePowerChart() {
    return Container(
      height: 230,
      color: Colors.white,
      child: ChargingStationPowerLineChart(
        powerData: controller.state.chaStaPowerDataList,
        powerUseRateData: controller.state.powerUseRateList,
        timeList: controller.state.powerTimeList,
      ),
    );
  }

  /// 实时功率模块
  Widget _createPowerModule() {
    return Container(
      padding: EdgeInsets.only(bottom: 10),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.only(top: 16, left: 16.w, bottom: 16),
            child: Text(
              ResKey.realTimePower.tr,
              style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w500),
            ),
          ),
          YtTimePicker(
            pickerMode: DateTimePickerMode.day,
            initialDateTime: DateTime(controller.targetYear,
                controller.targetMonth, controller.targetDay),
            onChange: (date, _) => controller.echoRealTimePowerDate(date),
          ),
          Row(
            children: [
              Spacer(),
              ShowFullScreenBtn(
                onTap: () {
                  Navigator.push(
                    Get.context!,
                    MaterialPageRoute(
                        builder: (context) => PowerFullScreenChart(
                              powerData: controller.state.chaStaPowerDataList,
                              powerUseRateData:
                                  controller.state.powerUseRateList,
                              timeList: controller.state.powerTimeList,
                            )),
                  );
                },
              )
            ],
          ),
          _generatePowerChart(),
        ],
      ),
    );
  }

  dataOverview() {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              StatisticsItemWidget(
                ResKey.deviceDailyChargeOrderNum.tr, //日充订单数
                controller.orderCount,
                ResKey.order.tr, // '单',
                '',
                isHome: false,
              ),
              Gaps.hGap10,
              StatisticsItemWidget(
                ResKey.deviceDailyChargeHourNum.tr, //日充电时长,
                controller.chargeTime,
                's',
                '',
                isHome: false,
              ),
            ],
          ),
          Gaps.vGap10,
          Row(
            children: [
              StatisticsItemWidget(
                ResKey.deviceDailyChargeCapacity.tr, //日充电量数,
                controller.chargeElectricity,
                'kWh',
                '',
                isHome: false,
              ),
              Gaps.hGap10,
              StatisticsItemWidget(
                ResKey.deviceDailyChargeFee.tr, //日充电费用,
                controller.orderAmount,
                ResKey.order.tr,
                '',
                isHome: false,
              ),
            ],
          ),
          Gaps.vGap10,
        ],
      ),
    );
  }

  /// 充电趋势柱状图
  Widget _generateTrendChart() {
    return SizedBox(
      width: double.infinity,
      height: 215 + 50,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: [
              Spacer(),
              ShowFullScreenBtn(
                onTap: () {
                  Navigator.push(
                    Get.context!,
                    MaterialPageRoute(
                        builder: (context) => ElectricityFullScreenChart(
                              timeList: controller.state.trendsTimeList,
                              chargingOrderCount:
                                  controller.state.chargingOrderCount,
                              chargingTimes: controller.state.chargingTimes,
                              chargingCapacityList:
                                  controller.state.chargingCapacityList,
                              chargingFee: controller.state.chargingFee,
                              // powerMaxValue: controller.electricityMaxValue,
                              // powerMinValue: controller.electricityMinValue,
                            )),
                  );
                },
              )
            ],
          ),

          /// 折线图
          Container(
            height: 214,
            color: Colors.white,
            width: double.infinity,
            child: ChargeStationTrendsChart(
              timeList: controller.state.trendsTimeList,
              chargingOrderCount: controller.state.chargingOrderCount,
              chargingTimes: controller.state.chargingTimes,
              chargingCapacityList: controller.state.chargingCapacityList,
              chargingFee: controller.state.chargingFee,
              // powerMaxValue: controller.electricityMaxValue,
              // powerMinValue: controller.electricityMinValue,
            ),
          ),
        ],
      ),
    );
  }

  /// 电量统计
  Widget _createTrendModule() {
    num textWidth = TextWidth.calculateTextSize(
        ResKey.deviceDailyElectricityStatistics.tr,
        TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.w400,
          color: controller.titleColor,
        ));

    return Container(
      margin: EdgeInsets.only(top: 10),
      child: Stack(
        children: <Widget>[
          Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    margin: EdgeInsets.only(top: 16, left: 16.w),
                    child: Text(
                      ResKey.deviceDailyElectricityStatistics.tr, //电量统计,
                      style: TextStyle(
                          fontSize: 16.sp, fontWeight: FontWeight.w500),
                    ),
                  ),
                  controller.state.terminalDeviceList.isEmpty ||
                          controller.chartId == 'Charge'
                      ? Gaps.empty
                      : Expanded(
                          child: GestureDetector(
                            onTap: () => controller.onClickTerminalTitle(),
                            child: Container(
                              margin: EdgeInsets.only(
                                  top: 6, right: 10.w, left: 10),
                              height: 40,
                              width:
                                  ScreenUtil().screenWidth - textWidth - 40.w,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Container(
                                    width: ScreenUtil().screenWidth -
                                        textWidth -
                                        80.w -
                                        24.w,
                                    child: Text(
                                      controller.terminalName!,
                                      maxLines: 2,
                                      style: TextStyle(
                                        fontSize: 14.sp,
                                        fontWeight: FontWeight.w400,
                                        color: controller.titleColor,
                                      ),
                                    ),
                                  ),
                                  Icon(
                                    controller.arrowDirection,
                                    color: controller.titleColor,
                                  )
                                ],
                              ),
                            ),
                          ),
                        ),
                ],
              ),
              Container(
                // margin: EdgeInsets.only(top: 60),
                child: YtTimePicker(
                  pickerMode: DateTimePickerMode.all,
                  initialDateTime: DateTime(controller.trendTargetYear,
                      controller.trendTargetMonth, controller.trendTargetDay),
                  onChange: (date, _) =>
                      controller.echoChageTrendDate(date, _!),
                ),
              ),
              // ChargeOverviewWidget(controller.orderCount, controller.chargeTime,
              //     controller.chargeElectricity, controller.orderAmount),
              dataOverview(),
              Container(
                margin: EdgeInsets.only(bottom: 10),
                child: _generateTrendChart(),
              ),
            ],
          ),
          Positioned(
              top: 40,
              width: ScreenUtil().screenWidth,
              child: Visibility(
                visible: controller.expand,
                child: Row(
                  children: [
                    Spacer(),
                    Container(
                      margin: const EdgeInsets.only(top: 20,bottom: 10),
                      padding: const EdgeInsets.only(right: 16,bottom: 10),
                      width: controller.containerWidth + 20 - 24.w,
                      height:
                          controller.state.terminalDeviceList.length * 40 + 15,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6),
                        boxShadow: const [
                          BoxShadow(
                            color: Colour.borderColor, // 设置阴影颜色
                            blurRadius: 10, // 阴影模糊程度
                            offset: Offset(0, 4), // 阴影偏移量
                          ),
                        ],
                        border:
                            Border.all(color: Colour.borderColor, width: 0.5),
                        color: Colors.white,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          ListView.builder(
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemBuilder: (BuildContext context, int index) {
                              return Container(
                                margin: EdgeInsets.only(left: 16.w),
                                height: 40,
                                alignment: Alignment.centerLeft,
                                child: GestureDetector(
                                  onTap: () {
                                    controller.selectedIndex = index;
                                    controller.terminalName = controller
                                        .state.terminalDeviceList[index].name;
                                    controller.trendDeviceId = int.parse(
                                        controller.state
                                            .terminalDeviceList[index].key!);
                                    controller
                                        .loadChargingTrendData()
                                        .then((value) => dismissLoading());
                                    controller.onClickTerminalTitle();

                                    controller.update();
                                  },
                                  child: Text(
                                    controller
                                        .state.terminalDeviceList[index].name,
                                    style: TextStyle(
                                      color: controller.selectedIndex == index
                                          ? Colour.primaryColor
                                          : Colour.mainTextColor,
                                    ),
                                  ),
                                ),
                              );
                            },
                            itemCount:
                                controller.state.terminalDeviceList.length,
                          )
                        ],
                      ),
                    ),
                    Gaps.hGap10
                  ],
                ),
              )),
        ],
      ),
    );
  }

  /// 上报数据模块
  Widget _createStatusInfoModule(Map<String, dynamic> config, Map? data) {
    return Column(
      children: [
        Container(
          alignment: Alignment.centerLeft,
          color: Colors.white,
          padding: EdgeInsets.only(left: 16.w, top: 16),
          child: Text(
            config['name'],
            style: TextStyle(
                color: Colour.mainTextColor,
                fontSize: 16.sp,
                fontWeight: FontWeight.w500),
          ),
        ),
        DynamicTabView(
          controller.setPushData(config['children'], data),
          isCanScroll: false,
        )
      ],
    );
  }

  /// 统计信息
  Widget _createStatiscsInfoModule(Map map) {
    return Column(
      children: [
        Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(left: 16.w, top: 16),
          child: Text(
            map['name'], //  '统计信息',
            style: TextStyle(
                color: Colour.mainTextColor,
                fontSize: 16.sp,
                fontWeight: FontWeight.w500),
          ),
        ),
        SizedBox(
          width: double.infinity,
          child: StasticsInfoWidget(
              deviceId: map['deviceId'],
              apiUrl: map['id'],
              modelList: map['children']
                  .map<StasticsInfoModel>((e) => StasticsInfoModel(
                      dataKey: e['id'],
                      dataName: e['name'],
                      dataType: e['dataType']))
                  .toList()),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ChargingStationController>(
      initState: (state) {
        Get.put(NewAirCoolingPageController());
        Log.d('deviceInfo = $deviceInfo');
        controller.deviceModel = deviceInfo;
        // if (controller.configMap.isEmpty) {
        Log.d('remoteControlMap = ');
        controller.getOssPhysicalModel(deviceInfo?.deviceId);
        // }
        // if (controller.state.chaStaRealPower.isEmpty) {
        Log.d('chaStaRealPower = ');
        controller.initData();
        // }
      },
      builder: (controller) {
        return Scaffold(
          appBar: AppBarWidget.withMorePopMenu(
              controller.deviceModel!.name.toString(),
              context,
              const GlobalObjectKey(RouterPath.chargingStationView),
              data: controller.actionList,
              onItemClick: (index, value) => controller.toService(value)),
          body: FuncUtils.isListEmpty(controller.pageMap['children'])
              ? Gaps.empty
              : ListView.separated(
                  padding: EdgeInsets.only(top: 10),
                  itemBuilder: (context, index) {
                    var child = controller.pageMap['children'][index];
                    if (child['type'] == 'component') {
                      switch (child['id']) {
                        case 'ChargeStack':
                        case 'Charge':
                          return Column(
                            children: [
                              KeepAliveWrapper(
                                  marginWrap(_createPowerModule())),
                              KeepAliveWrapper(
                                  marginWrap(_createTrendModule())),
                            ],
                          );
                        // case 'getChargeStatistics':
                        //   return KeepAliveWrapper(_createStatiscsInfoModule());
                      }
                    } else if (child['type'] == 'group') {
                      if (child['dataInterceptor'] == 'request') {
                        return KeepAliveWrapper(
                            marginWrap(_createStatiscsInfoModule(child)));
                      }
                      return StreamBuilder(
                          stream: controller.streamController?.stream
                              .asBroadcastStream(),
                          builder: (context, snapshot) => KeepAliveWrapper(
                              marginWrap(_createStatusInfoModule(
                                  child, snapshot.data))));
                    }
                  },
                  itemCount: controller.pageMap['children'].length,
                  separatorBuilder: (context, index) => Gaps.empty,
                ),
        );
      },
    );
  }

  Widget marginWrap(Widget child) {
    return Container(
      margin: EdgeInsets.only(left: 12.w, right: 12.w, top: 10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8), color: Colors.white),
      child: child,
    );
  }
}
